/**
 * author:wos
 * time:2024-1-4
 * title:获取用户的菜单
 */

async function getRouters(ctx, next) {
    let user = await global.getUser(ctx)
    if (!user) {
        global.goLogin(ctx)
        return false
    }
    let menuSql = `SELECT menuId FROM sys_role_menu WHERE roleId IN (SELECT sys_user_role.roleId FROM sys_user_role, sys_role WHERE sys_user_role.roleId = sys_role.roleId and sys_user_role.userId = (SELECT userId FROM sys_user WHERE username = '${ctx.username}') and sys_role.status = 0 )`
    let rsMenus = await global.query(menuSql) //获取权限

    let myMenus = []
    if(user.type == '1'){ //高级管理员
        myMenus.push("*")
    }else{
        for (let i in rsMenus){
            myMenus.push(rsMenus[i].menuId)
        }
    }

    let menu = await global.query(`select * from sys_menu where status = '0'  order by orderNum asc`)
    let data = formatMenu(menu, 0, myMenus)
    global.response(ctx, {
        "status":200,
        "code": 200,
        "data": data,
        "msg":'success'
    })
}

/**
 * 格式化目录菜单
 * @param menu
 * @param parentId
 * @returns {[]}
 */
function formatMenu(menu, parentId, myMenus){
    let result = []
    for(let i in menu){
        if(menu[i].parentId == parentId){
            let item = {
                "name": menu[i].menuName,
                "path": menu[i].path,
                "hidden": menu[i].visible,
                "redirect": menu[i].isFrame === '1' ? menu[i].path : 'noRedirect',
                "component": menu[i].menuType === 'M' ? 'Layout' : menu[i].component ,
                "alwaysShow": menu[i].status,
                "meta": {
                    "title": menu[i].menuName,
                    "icon": menu[i].icon,
                    "noCache": menu[i].isCache,
                    "link": menu[i].menuName
                },
                "menuType": menu[i].menuType
            }
            let children = formatMenu(menu, menu[i].menuId, myMenus)
            if(children.length > 0){
                item.children = children
                result.push(item)
            }
            else if (myMenus[0] === "*") {
                result.push(item)
            }
            else if (myMenus[0] !== "*"){
                if(myMenus.indexOf(menu[i].menuId)>-1){
                    result.push(item)
                }
            }

        }
    }
    //排序
    result.sort((a, b) => {
        return Number(a.orderNum) - Number(b.orderNum);
    })
    return result
}

module.exports = getRouters